package io.adrainty.bolee.file.handler;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.text.StrPool;
import io.adrainty.bolee.framework.commons.basic.ResponseCode;
import io.adrainty.bolee.framework.commons.exception.AppException;
import jakarta.annotation.Resource;

import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.time.LocalDate;
import java.util.HashMap;
import java.util.Map;

/**
 * @author AdRainty
 * @version V1.0.0
 * @since 2025/8/18 上午12:33
 */
public abstract class AbsFileStorageHandler implements FileStorageHandler {

    @Resource
    protected FileStorageProperties commonProperties;

    protected static final Map<String,String> metaMimeTypeMap = new HashMap<>();

    static {
        metaMimeTypeMap.put(".docx","application/vnd.openxmlformats-officedocument.wordprocessingml.document");
        metaMimeTypeMap.put(".doc","application/msword");
        metaMimeTypeMap.put(".ppt","application/x-ppt");
        metaMimeTypeMap.put(".xls","application/vnd.ms-excel");
        metaMimeTypeMap.put(".xhtml","text/html");
        metaMimeTypeMap.put(".htm","text/html");
        metaMimeTypeMap.put(".html","text/html");
        metaMimeTypeMap.put(".jpe","image/jpg");
        metaMimeTypeMap.put(".jpeg","image/jpg");
        metaMimeTypeMap.put(".jpg","image/jpg");
        metaMimeTypeMap.put(".png","image/jpg");
        metaMimeTypeMap.put(".mp4","video/mp4");
        metaMimeTypeMap.put(".wmv","video/x-ms-wmv");
        metaMimeTypeMap.put(".pdf","application/pdf");
        metaMimeTypeMap.put(".mp3","audio/mp3");
    }

    protected final String buildDirPath(String fileName) {
        LocalDate localDate = LocalDate.now();
        return String.join(StrPool.SLASH,
                String.valueOf(localDate.getYear()), String.valueOf(localDate.getMonthValue()),
                String.valueOf(localDate.getDayOfMonth()), fileName);
    }

    @Override
    public String getFileContent(String bucketName, String pathUrl) {
        try (InputStream is = downloadFile(bucketName, pathUrl)) {
            return IoUtil.read(is, StandardCharsets.UTF_8);
        } catch (IOException e) {
            throw new AppException(ResponseCode.FILE_READ_ERROR);
        }
    }

}
